package com.cos.zuul.filer;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.scenario.effect.FilterContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: COS
 * @time: 2022/4/29 15:26
 * @description:
 */
//@Component
public class TestZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //pre post error route
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //可以负数 0  整数
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("前置过滤器启动啦啦啦啦");
        //获取reqeust 获取参数验证token
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取httprequest
        HttpServletRequest request = currentContext.getRequest();
        //request
        String token = request.getParameter("token");
        if (token==null||!token.equals("admin")) {
            //验证失败
//            currentContext.setSendZuulResponse(false);
            //响应401异常
            currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }else{
            //验证成功
            //验证失败
            currentContext.setSendZuulResponse(true);
            //响应401异常
            currentContext.setResponseStatusCode(HttpStatus.OK.value());
        }

        currentContext.setSendZuulResponse(true);
        return null;
    }
}
